package com.chigga.application.hanlder.login.exception;

import com.chigga.common.constants.HttpStatusConstant;
import com.chigga.common.core.domain.ResponseResult;
import com.chigga.common.utils.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证成功(Authentication), 但无权访问时。会执行这个方法
 * 或者SpringSecurity框架捕捉到  AccessDeniedException时，会转出
 * @author DefChigga
 */
public class CustomAuthorizationExceptionHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 设置状态码，响应/编码类型
        response.setStatus(HttpStatusConstant.FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        // 把对象转为 json 字符串
        PrintWriter writer = response.getWriter();
        writer.print(JSON.stringify(ResponseResult.failure(HttpStatusConstant.FORBIDDEN, "无权访问")));
        writer.flush();
        writer.close();
    }
}
